import { forwardRef, Ref, useCallback, useImperativeHandle, useState } from 'react';
import ImgCrop from 'antd-img-crop';
import { getMessage, TextWidget } from '@inbiz/react';
import { Form, FormInstance, Input, message, Select, Upload } from 'antd';
import { InbizIcon } from '@inbiz/utils';
import { IconGroupType } from '../service';
import '../index.less';

type IUploadCustomIcon = {
  groupData: IconGroupType[];
  ref: Ref<IUploadContent>;
  checkSelectGroup: IconGroupType;
};
export type IUploadContent = {
  getForm: () => FormInstance<any>;
};

const UploadCustomIcon = (props: IUploadCustomIcon, ref: Ref<IUploadContent>) => {
  const { groupData, checkSelectGroup } = props;
  const { Option } = Select;
  const [form] = Form.useForm();
  const [iconUrl, setIconUrl] = useState<string>();
  // 判断文件类型
  const checkFileType = useCallback((file) => {
    let isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/svg+xml' ||
      file.type === 'image/bmp' ||
      file.type === 'image/jpg' ||
      file.type === 'image/gif';
    // 和后台提示信息格式保持一致：文件格式必须为.jpg,.jpeg,.png,.gif,.bmp,.svg,.tiff
    const len = file.name.length;
    const fileSuffix = file.name.substr(len - 4, len);
    if (fileSuffix == 'jfif') {
      isJpgOrPng = false;
    }
    return isJpgOrPng;
  }, []);

  // 上传的逻辑
  function getBase64(icon: File, callback: (iconUrl: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(icon);
  }
  const uploadOnChange = (e: any) => {
    const isJpgOrPng = checkFileType(e?.file);
    const isLt10M = e?.file?.size / 1024 / 1024 < 10;
    if (!isJpgOrPng || !isLt10M) {
      setIconUrl('');
      form.setFields([{ name: 'iconFile', value: undefined }]);
    }
    if (!isLt10M) {
      message.error(getMessage('IconPicker.uploadIconSize') + '!');
      return false;
    }
    console.log(e, 111)

    // 走裁剪的图标的上传方式(图标名称输入框自动赋值)
    // if (e.file?.status) {
    //   if (e.file?.status === 'done') {
    //     getBase64(e.file.originFileObj, (iconUrl: any) => {
    //       setIconUrl(iconUrl);
    //     });
    //     form.setFieldsValue({ name: e.file?.name?.substring(0, e.file?.name?.indexOf('.')) });
    //   }
    // } else {
    //   // 不走裁剪的图标的上传方式(图标名称输入框自动赋值)
    //   if (
    //     e.file?.type === 'image/svg+xml' ||
    //     e.file?.type === 'image/gif' ||
    //     e.file?.type === 'image/png' ||
    //     e.file?.type === 'image/jpg' ||
    //     e.file?.type === 'image/jpeg' ||
    //     e.file?.type === 'image/bmp'
    //   ) {
    //     getBase64(e.file, (iconUrl: any) => {
    //       setIconUrl(iconUrl);
    //     });
    //     form.setFieldsValue({ name: e.file?.name?.substring(0, e.file?.name?.indexOf('.')) });
    //   }
    // }
    if (
      e.file?.type === 'image/svg+xml' ||
      e.file?.type === 'image/gif' ||
      e.file?.type === 'image/png' ||
      e.file?.type === 'image/jpg' ||
      e.file?.type === 'image/jpeg' ||
      e.file?.type === 'image/bmp'
    ) {
      getBase64(e.file?.originFileObj || e.file, (iconUrl: any) => {
        setIconUrl(iconUrl);
      });
      form.setFieldsValue({ name: e.file?.name?.substring(0, e.file?.name?.indexOf('.')) });
    }
  };

  // ref
  useImperativeHandle(ref, () => ({
    getForm: () => {
      return form;
    },
  }));

  // 上传前做的事儿
  const beforeUpload = (file: any) => {
    const isJpgOrPng = checkFileType(file);
    if (!isJpgOrPng) {
      message.error(getMessage('IconPicker.uploadIconFormat') + '!');
    }
  };

  // 裁剪前
  const beforeCrop = (e: any) => {
    // 不符合类型、大小时，不出现裁剪
    const isJpgOrPng = checkFileType(e);
    if (!isJpgOrPng) {
      message.error(getMessage('IconPicker.uploadIconFormat') + '!');
      return false;
    }
    return false;
  };

  return (
    <div className="container">
      <Form
        name="basic"
        initialValues={{
          iconGroupOutId:
            checkSelectGroup.OutId?.length > 0
              ? checkSelectGroup.OutId
              : groupData?.length > 0 && groupData[0].IsDefault
                ? groupData[0].OutId
                : '',
        }}
        preserve={false}
        form={form}
      >
        <div className="upload">
          <Form.Item
            name="iconFile"
            rules={[{ required: true, message: getMessage('IconPicker.pleaseUploadIcon') }]}
          >
            <SplitUploadItem
              iconUrl={iconUrl}
              onChange={uploadOnChange}
              beforeCrop={beforeCrop}
              beforeUpload={beforeUpload}
            />
          </Form.Item>

          <div className="descript">
            <span>
              <TextWidget>IconPicker.supportUpload</TextWidget>JPG、JPEG、BMP、PNG、GIF、SVG
              <TextWidget>IconPicker.format</TextWidget>
            </span>
          </div>
        </div>
        <div className="message">
          <div>
            <label>
              <TextWidget>IconPicker.belongGroup</TextWidget>
            </label>
            <Form.Item
              name="iconGroupOutId"
              // label='所属分组'
              colon={false}
              rules={[{ required: true, message: getMessage('IconPicker.pleaseSelectGroup') }]}
            >
              <Select style={{ width: 261, height: 38 }}>
                {groupData?.length > 0 &&
                  groupData.map((nowGroup) => {
                    return <Option key={nowGroup.OutId}>{nowGroup.Name}</Option>;
                  })}
              </Select>
            </Form.Item>
          </div>
          <div>
            <label>
              <TextWidget>IconPicker.iconName</TextWidget>
            </label>
            <Form.Item
              name="name"
              // label='图标名称'
              colon={false}
              rules={[{ required: true, message: getMessage('IconPicker.pleaseEnterName') }]}
            >
              <Input
                placeholder={getMessage('IconPicker.pleaseEnterName')}
                autoComplete="off"
                style={{ width: 261, height: 38 }}
              />
            </Form.Item>
          </div>
        </div>
      </Form>
    </div>
  );
};
export default forwardRef(UploadCustomIcon);

const SplitUploadItem = ({
  iconUrl,
  onChange,
  beforeUpload,
  beforeCrop,
}: {
  onChange?: (file: any) => void;
  beforeUpload: (file: any) => boolean;
  beforeCrop: (e: any) => boolean;
  iconUrl?: string;
}) => {
  return (
    <ImgCrop
      beforeCrop={beforeCrop}
      quality={1}
      rotationSlider
      modalCancel={getMessage('IconPicker.cancelText')}
      modalOk={getMessage('IconPicker.okText')}
    >
      <Upload
        listType="picture-card"
        showUploadList={false}
        onChange={onChange}
        beforeUpload={beforeUpload}
        // 自定义处理函数将导致onChange事件status状态不更新
        customRequest={(props) => props.onSuccess?.({ body: 'success' })}
      >
        {iconUrl && iconUrl?.length > 0 ? (
          <InbizIcon type={iconUrl} style={{ width: 120, height: 120 }} />
        ) : (
          <InbizIcon type="icon-process-xinjianliucheng-shangchuan" style={{ fontSize: 31 }} />
        )}
      </Upload>
    </ImgCrop>
  );
};
